const express = require("express");
const app = express();

function* createCounter() {
  let i = 0;
  while (true) {
    yield ++i;
  }
}

const counter = createCounter();

const setProperty = (obj, property, key, value) => {
  if (!obj[property]) {
    obj[property] = {};
  }
  obj[property][key] = value;
};

const m1 = (req, res, next) => {
  console.log("m1 start");
  setProperty(res, "m", "m1", counter.next().value);
  next();
  setProperty(res, "m", "m1a", counter.next().value);
  console.log("m1 end");
};

const m2 = (req, res, next) => {
  console.log("m2 start");
  setProperty(res, "m", "m2", counter.next().value);
  next();
  setProperty(res, "m", "m2a", counter.next().value);
  console.log("m2 end");
};

const m3 = (req, res, next) => {
  console.log("m3 start");
  setProperty(res, "m", "m3", counter.next().value);
  next();
  setProperty(res, "m", "m3a", counter.next().value);
  console.log("m3 end");
};

app.use(m1);
app.use(m2);
app.use(m3);

app.get("/", (req, res) => {
  console.log(JSON.stringify(res.m));
  res.json(res.m);
});

app.listen(3010);
